<template>
  <div class="user-manager">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics">
      <el-col :span="6" v-for="item in statisticsData" :key="item.title">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-value">{{ item.value }}</div>
          <div class="stat-title">{{ item.title }}</div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 查询条件 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="用户名">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            style="min-width: 140px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>          
        </el-form-item>
      </el-form>
    </div>
    <!-- 用户列表 -->
    <el-table :data="userList" stripe border v-loading="loading">
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column prop="avatar" label="头像" width="80">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="registerTime" label="注册时间" width="180" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status ? 'success' : 'danger'">
            {{ row.status ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleEdit(row)"
          >
            编辑
          </el-button>
          <el-button 
            :type="row.status ? 'danger' : 'success'"
            size="small" 
            @click="handleToggleStatus(row)"
          >
            {{ row.status ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 编辑用户弹窗 -->
    <el-drawer 
      v-model="showEditDialog"
      :title="'编辑用户 - ' + userForm.username"
      size="500px"
      :destroy-on-close="true"
    >
      <div class="edit-user-form">
        <el-form 
          :model="userForm" 
          :rules="userRules"
          ref="userFormRef"
          label-width="100px"
        >
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <el-avatar 
                :size="100" 
                :src="userForm.avatar"
                class="avatar-preview"
              />
              <div class="upload-mask">
                <i class="el-icon-camera"></i>
                <span>更换头像</span>
              </div>
            </el-upload>
          </div>

          <el-form-item label="用户名">
            <el-input v-model="userForm.username" disabled></el-input>
            <div class="form-tip">用户名不可修改</div>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userForm.phone">
              <template #prepend>+86</template>
            </el-input>
          </el-form-item>
          
          <el-form-item label="用户等级">
            <el-select v-model="userForm.level" placeholder="请选择用户等级">
              <el-option label="普通会员" value="normal" />
              <el-option label="黄金会员" value="gold" />
              <el-option label="白金会员" value="platinum" />
            </el-select>
          </el-form-item>

          <el-form-item label="账号状态">
            <el-switch
              v-model="userForm.status"
              active-text="启用"
              inactive-text="禁用"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>

          <el-form-item label="备注">
            <el-input
              type="textarea"
              v-model="userForm.remark"
              rows="3"
              placeholder="请输入用户备注信息"
            />
          </el-form-item>
        </el-form>

        <div class="user-statistics">
          <h4>用户数据统计</h4>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="label">注册时间</div>
              <div class="value">{{ userForm.registerTime }}</div>
            </div>
            <div class="stat-item">
              <div class="label">订单数量</div>
              <div class="value">{{ userForm.orderCount || 0 }}</div>
            </div>
            <div class="stat-item">
              <div class="label">消费金额</div>
              <div class="value">¥{{ userForm.totalSpent || '0.00' }}</div>
            </div>
          </div>
        </div>

        <div class="drawer-footer">
          <el-button @click="showEditDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUser">确定</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from "@element-plus/icons-vue"

// 模拟数据
const mockUsers = Array.from({ length: 100 }).map((_, index) => ({
  id: index + 1,
  username: `user${index + 1}`,
  phone: `138${String(index + 1).padStart(8, '0')}`,
  avatar: `https://picsum.photos/200/200?random=${index}`,
  registerTime: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000).toLocaleString(),
  status: Math.random() > 0.1
}))

// 列表数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchQuery = ref('')

// 表单数据
const showEditDialog = ref(false)
const userFormRef = ref(null)
const userForm = reactive({
  id: null,
  username: '',
  phone: '',
  status: true
})

// 表单验证规则
const userRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

// 统计数据
const statisticsData = ref([
  { title: '用户总数', value: 1234 },
  { title: '正常用户', value: 1200 },
  { title: '禁用用户', value: 34 },
  { title: '本月新增', value: 56 }
])

// 查询表单
const searchForm = reactive({
  username: '',
  phone: '',
  status: null
})

// 获取用户列表
const getUserList = () => {
  loading.value = true
  setTimeout(() => {
    const filtered = searchQuery.value
      ? mockUsers.filter(u => 
          u.username.includes(searchQuery.value) || 
          u.phone.includes(searchQuery.value)
        )
      : mockUsers
    
    total.value = filtered.length
    const start = (currentPage.value - 1) * pageSize.value
    userList.value = filtered.slice(start, start + pageSize.value)
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getUserList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    username: '',
    phone: '',
    status: null
  })
  currentPage.value = 1
  getUserList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getUserList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 编辑用户
const handleEdit = (user) => {
  Object.assign(userForm, user)
  showEditDialog.value = true
}

// 保存用户
const handleSaveUser = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    const index = userList.value.findIndex(u => u.id === userForm.id)
    if (index !== -1) {
      userList.value[index] = { ...userList.value[index], ...userForm }
    }
    ElMessage.success('保存成功')
    showEditDialog.value = false
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

// 切换用户状态
const handleToggleStatus = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status ? '禁用' : '启用'}该用户吗？`,
      '提示'
    )
    user.status = !user.status
    ElMessage.success(`${user.status ? '启用' : '禁用'}成功`)
  } catch {
    // 取消操作
  }
}

// 初始化
getUserList()
</script>

<style lang="scss" scoped>
.user-manager {
  padding: 20px;

  .statistics {
    margin-bottom: 20px;
    .stat-card {
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
      }
      .stat-title {
        color: #666;
      }
    }
  }

  .search-section {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}

.edit-user-form {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .avatar-upload {
    text-align: center;
    margin-bottom: 30px;

    .avatar-uploader {
      position: relative;
      display: inline-block;
      cursor: pointer;

      .avatar-preview {
        transition: all 0.3s;
      }

      .upload-mask {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: white;
        opacity: 0;
        transition: opacity 0.3s;

        i {
          font-size: 24px;
          margin-bottom: 5px;
        }

        span {
          font-size: 12px;
        }
      }

      &:hover {
        .upload-mask {
          opacity: 1;
        }
      }
    }
  }

  .form-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
  }

  .user-statistics {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;

    h4 {
      margin-bottom: 15px;
      color: #666;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 15px;

      .stat-item {
        background: #f8f8f8;
        padding: 15px;
        border-radius: 4px;
        text-align: center;

        .label {
          color: #666;
          font-size: 12px;
          margin-bottom: 5px;
        }

        .value {
          font-size: 16px;
          font-weight: bold;
          color: #1890ff;
        }
      }
    }
  }

  .drawer-footer {
    margin-top: auto;
    padding-top: 20px;
    border-top: 1px solid #f0f0f0;
    text-align: right;

    .el-button {
      margin-left: 8px;
    }
  }
}
</style>
